
(function(i) {
    var t = setInterval(function () {
	if (document.readyState=="loaded"||document.readyState=="complete")
            clearInterval(t), i();
        }, 0);
})(coolSearchInit);

var url='';
var sel;

var frame_id='';

var Xoffset;
var Yoffset=32;
var zoomLevel;

function coolSearchInit() {
    var engines=document.createElement('div');
    engines.setAttribute('id','engines');
    engines.style.display='none';
    document.body.appendChild(engines);
    
    safari.self.addEventListener("message", respondToMessage, false);
    safari.self.tab.dispatchMessage("request_init_args", "");

    var detP=document.createElement('div');
    var detS=document.createElement('div');
    document.body.appendChild(detP);
    document.body.appendChild(detS);
    detP.outerHTML='<div id="detP" style="top:2px;left:10%;position:absolute;"></div>';
    detS.outerHTML='<div id="detS" style="top:2px;position:absolute;"></div>';
    _G('detS').style.left=_G('detP').offsetLeft+"px";

    initMain();  
}

function initMain() {
document.addEventListener('dragstart', function(ev) {
    sel = document.getSelection().toString().trim();
    if(sel.length>0) {
        if(isUrl(sel)) {
	    url = sel;
	    return;
	}
        decidePos(ev);
	engines.style.display='block';
    }
}, true);

document.addEventListener('mouseup', onMouseUp, true);
}

function onMouseUp() {
    if(url!='') {
        safari.self.tab.dispatchMessage("open_url", url);
        url='';
    }
    engines.style.display='none';
}

function frame_dragstart(msg) {
    sel=msg.sel;
    if(sel.length>0) {
        if(isUrl(sel)) {
            url = sel;
            return;
        }
        frame_id=msg.callbackId;
        var ev=msg.event;
        var pageOffset={X:0, Y:0};
        var node=frame_id;
        while (node && node != document.body) {
        	try{
        		if(node.style.position == 'fixed') {
        			pageOffset={X:window.pageXOffset, Y:window.pageYOffset};
        			break;
        		}
        	} catch (e) {
        		alert(node.tagName);
        	}
        	node=node.parentNode;
        }
        ev.pageX=ev.x + pageOffset.X;
        ev.pageY=ev.y + pageOffset.Y;
        decidePos(ev);
        engines.style.display='block';
    }
}


function respondToMessage(event) {
    if (event.name == "init_args") {
        var msg=event.message;
        var egsArray=msg.Engines;
        Xoffset=egsArray.length*24.0;
        zoomLevel=(msg.zoomLevel==null)?zoomLevel:msg.zoomLevel;
	createSearchEnginesDiv(egsArray);
    } else if(event.name == "frame_dragstart") {
    	var msg=event.message;
    	var href=msg.href;

    	var iframes=document.getElementsByTagName('iframe');
    	if(iframes) {
    		for(var i=0; i<iframes.length; ++i) {
    			if(iframes[i].src==href) {
    				frame_id = iframes[i];
    				break;
    			}
    		}
    	}
    	var frames=document.getElementsByTagName('frame');
    	if(frames) {
        	for(var i=0; i<frames.length; ++i) {
    			if(frames[i].src==href) {
    				frame_id = frames[i];
    				break;
    			}
    		}
    	}
    	
    	frame_dragstart({callbackId:frame_id, sel:msg.sel, event:msg.event});
    } else if(event.name == "frame_dragend") {
    	onMouseUp();
    } else if(event.name == "zoom_change") {
        zoomLevel=event.message;
    }
	
}

function createSearchEnginesDiv(searchegs) {
    engines.innerHTML='';
    var len=searchegs.length;
    if(len==0) return;
    for(var i=0; i<len; ++i) { 
        var egdiv=document.createElement('img');
        egdiv.className='searchicon';
        egdiv.src=getIMG(searchegs[i]+'.png');
        egdiv.setAttribute('id',searchegs[i]);
        engines.appendChild(egdiv);
    
        egdiv.ondragenter = function(e) {
	    e.target.style.opacity='1.0';
	}
	egdiv.ondragleave = function(e) {
            e.target.style.opacity='0.6';
        }
	egdiv.ondragover = function(e) {
//	    e.preventDefault();
	    return false;
	}
	egdiv.ondrop = function(ev) {
	    var query=encodeURIComponent(sel);
	    ev.target.style.opacity='0.6';
	    var id=ev.target.getAttribute('id');
	    ev.preventDefault();
	    safari.self.tab.dispatchMessage("search", {id:id, query:query});
	    engines.style.display='none';
        }
    }

}

function _G(objID) {
        return document.getElementById(objID);
}

function detectZoom() {
    var sL=_G('detS').offsetLeft;
    var pL=_G('detP').offsetLeft;
    var factor=sL/pL;
    return factor;
}

function decidePos(ev) {
    var zoom_factor=zoomLevel*detectZoom();

    var left_margin=Math.max(this.screenX, 0);
    var right_margin=Math.min(this.outerWidth+this.screenX, screen.width);
    var bottom_margin=Math.min(this.outerHeight+this.screenY, screen.height);   
 
    var detX=right_margin-ev.screenX;
    var detY=bottom_margin-ev.screenY;

    if(frame_id!='') {
        var offset=calcOffset(frame_id);
        ev.pageX=ev.pageX+offset.left*zoom_factor;
        ev.pageY=ev.pageY+offset.top*zoom_factor;
        frame_id='';
    }

    if(ev.screenX-Xoffset*zoom_factor<left_margin) engines.style.posLeft=(ev.pageX+left_margin-ev.screenX)/zoom_factor;
    else if((Xoffset+2)*zoom_factor>detX)
        engines.style.posLeft=(ev.pageX+detX-16)/zoom_factor-2*Xoffset-4;
    else
        engines.style.posLeft=ev.pageX/zoom_factor-Xoffset;
    if(engines.style.posLeft<0) engines.style.posLeft=0;
    
    if((Yoffset+48+2)*zoom_factor>detY)
        engines.style.posTop=ev.pageY/zoom_factor-Yoffset-48;
    else
        engines.style.posTop=ev.pageY/zoom_factor+Yoffset;
}

function calcOffset(obj) {
    var offset={left:0, top:0};
    do {
	offset.left+=obj.offsetLeft;
   	offset.top+=obj.offsetTop;
    }
    while(obj=obj.offsetParent);
    return offset;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function getIMG(imgName) {
    return safari.extension.baseURI + "img/" + imgName;
}

function isUrl(text) {
    var regex = /^(https?|ftp|gopher|telnet|file|notes|ms-help):\/\//;
    return regex.test(text);
}